/*************************************************************************
    > File Name: character_app.c
    > Created Time: Wed 30 Dec 2020 22:35:58 PM PST
 ************************************************************************/
#include "stdio.h"
#include "unistd.h"
#include "sys/types.h"
#include "sys/stat.h"
#include "fcntl.h"
#include "stdlib.h"
#include "string.h"
#include <linux/ioctl.h>

#define LUAN_TEST_MAGIC    'L'
#define LUAN_TEST_CMD_MAX   5
#define READ_LENGTH_CMD _IOR(LUAN_TEST_MAGIC,  1, int)

#define OPERATE_FILE_PATH "/dev/character_device"

static char usrdata[] = {"usr data!"};

int main(int argc,char *argv[])
{
	int fd,ret;
	int read_length = 0;
	char *filename;
	char readbuf[100],writebuf[100];

	if(atoi(argv[1]) == 1)
	{
		if(argc != 2)
		{
			printf("Error Usage!:%d\n",argc);
			return -1;
		}
	}
	else if(atoi(argv[1]) == 2)
	{
		if(argc != 3)
		{
			printf("Error Usage!:%d\n",argc);
			return -1;
		}
	}
	filename = OPERATE_FILE_PATH;

	fd = open(filename,O_RDWR);
	if(fd < 0)
	{
		printf("Can't open file %s\r\n",filename);
		return -1;
	}
	ret = ioctl(fd,READ_LENGTH_CMD,&read_length);
	if(ret < 0)
	{
		printf("ioctl read error:%d\r\n",ret);
		return -1;
	}
	printf("Ioctl Read Length:%d,ret:%d\r\n",read_length,ret);
	if(atoi(argv[1]) == 1)
	{
		ret = read(fd,readbuf,read_length);
		if(ret < 0)
		{
			printf("read file %s fialed!\r\n",filename);
		}
		else
		{
			printf("read data:%s\r\n",readbuf);
		}
	}
	if(atoi(argv[1]) == 2)
	{
		memcpy(writebuf,argv[2],strlen(argv[2]));
		printf("write:%s,size:%d\n",argv[2],strlen(argv[2]));
		ret = write(fd,writebuf,strlen(argv[2]));
		if(ret<0)
		{
			printf("write file %s failed!\r\n",filename);
		}
	}
	ret = close(fd);
	if(ret < 0)
	{
		printf("Can't close file%s\n",filename);
	}
	return 0;
}
